<template>
  <!-- 表单 -->
  <el-card style="margin: 10px 0px">
    <el-button icon="Plus" type="primary" size="default" @click="addDept"
      >添加机构</el-button
    >
    <el-table style="margin: 10px 0px" rowKey="id" :data="deptArr" stripe>
      <el-table-column type="selection"></el-table-column>
      <el-table-column label="ID" prop="id"></el-table-column>
      <el-table-column
        label="名称"
        prop="name"
        treeKey="id"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="上级机构"
        prop="parentName"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="排序"
        prop="orderNum"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="创建人"
        prop="createBy"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="创建时间" prop="createTime" show-overflow-tooltip>
        <template #default="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="150px">
        <template #default="scope">
          <el-button
            type="primary"
            link
            size="small"
            icon="Edit"
            @click="updateDept(scope.row)"
            >编辑</el-button
          >
          <el-popconfirm
            :title="`你确定要删除吗?`"
            width="260px"
            @confirm="deleteDept(scope.row)"
          >
            <template #reference>
              <el-button link type="danger" size="small" icon="Delete"
                >删除</el-button
              >
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
  <!-- 新增或者编辑 -->
  <drawer ref="drawerRef" @cancel="handleCancel" @submit="handleSubmit">
    <template v-slot:title>
      <h4>{{ formParams.id ? "更新机构" : "添加机构" }}</h4>
    </template>
    <template v-slot:content>
      <el-form
        ref="formRef"
        label-width="auto"
        :model="formParams"
        :rules="rules"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="formParams.name" placeholder="名称"></el-input>
        </el-form-item>
        <el-form-item label="上级机构" prop="parentName">
          <popup-tree-input
            :data="popupTreeData"
            :prop="
              formParams.parentName == null ? '顶级菜单' : formParams.parentName
            "
            :nodeKey="'' + formParams.parentId"
            @handleCurrentChange="handleCurrentChanges"
          >
          </popup-tree-input>
        </el-form-item>
        <el-form-item label="排序编号" prop="orderNum">
          <el-input-number
            v-model="formParams.orderNum"
            controls-position="right"
            :min="0"
            label="排序编号"
          ></el-input-number>
        </el-form-item>
      </el-form>
    </template>
  </drawer>
</template>
<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from "vue";
import { reqDeptFindTree, reqDeptDelete, reqDeptSave } from "@/api/acl/dept";
import { formatDateTime } from "@/utlis/datetime";
import { validatorNames, validatorParentName } from "@/utlis/validator";
import { ElMessage } from "element-plus";
onMounted(() => {
  inintData();
});
const deptArr = ref([]);
const drawerRef = ref();
const formRef = ref();
const popupTreeData = ref([] as any);
const formParams = reactive({
  id: undefined,
  name: "",
  parentId: 0,
  parentName: "",
  orderNum: 0,
});
const inintData = async () => {
  const res: any = await reqDeptFindTree();
  if (res.code === 200) {
    deptArr.value = res.data;
    popupTreeData.value = getParentMenuTree(res.data);
  }
};
const getParentMenuTree = (tableTreeDdata: string[]) => {
  let parent = {
    parentId: 0,
    name: "顶级菜单",
    children: tableTreeDdata,
  };
  return [parent];
};
//添加
const addDept = () => {
  drawerRef.value.open();
  //清空数据
  Object.assign(formParams, {
    id: undefined,
    name: "",
    parentId: 0,
    parentName: "",
    orderNum: 0,
  });
  nextTick(() => {
    formRef.value.clearValidate("label");
  });
};
//删除
const deleteDept = async (row: any) => {
  const params = getDeleteIds([], row);
  const res = await reqDeptDelete(params);
  if (res.code === 200) {
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    inintData();
  } else {
    ElMessage({
      type: "error",
      message: res.msg,
    });
  }
};
// 获取删除的包含子菜单的id列表
const getDeleteIds = (ids: any, row: any) => {
  ids.push({ id: row.id });
  if (row.children != null) {
    for (let i = 0, len = row.children.length; i < len; i++) {
      getDeleteIds(ids, row.children[i]);
    }
  }
  return ids;
};
//编辑
const updateDept = (row: any) => {
  addDept();
  //存储收集已有的账号信息
  Object.assign(formParams, row);
};
//关闭
const handleCancel = () => {
  drawerRef.value.close();
};
// 表单提交
const handleSubmit = async () => {
  //点击保存按钮的时候,务必需要保证表单全部复合条件在去发请求
  await formRef.value.validate();
  //按钮加载
  drawerRef.value.showloading();
  let params: any = Object.assign({}, formParams);
  const res = await reqDeptSave(params);
  //添加或者更新成功
  if (res.code == 200) {
    //关闭抽屉
    handleCancel();
    //提示消息
    ElMessage({
      type: "success",
      message: formParams.id ? "编辑成功" : "添加成功",
    });
    drawerRef.value.hideloading();
    //获取最新的全部账号的信息
    inintData();
  } else {
    //关闭抽屉
    handleCancel();
    //提示消息
    ElMessage({
      type: "error",
      message: res.msg,
    });
    drawerRef.value.hideloading();
  }
};
// 菜单树选中
const handleCurrentChanges = (data: any) => {
  formParams.parentId = data.id;
  formParams.parentName = data.name;
};
//表单校验的规则对象
const rules = {
  //名称
  name: [{ required: true, trigger: "blur", validator: validatorNames }],
  //机构
  parentName: [
    { required: true, trigger: "change", validator: validatorParentName },
  ],
};
</script>
<style lang="scss" scoped></style>
